# Maintainer: LI Xuzhang <lixuzhang@gmail.com>

_realname=postgis
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=3.3.1
pkgrel=2
pkgdesc="Spatial and Geographic objects for PostgreSQL (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://postgis.net/"
license=('spdx:GPL-2.0-or-later')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc" "${MINGW_PACKAGE_PREFIX}-autotools")
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-geos"
         "${MINGW_PACKAGE_PREFIX}-gettext"
         "${MINGW_PACKAGE_PREFIX}-json-c"
         "${MINGW_PACKAGE_PREFIX}-libxml2"
         "${MINGW_PACKAGE_PREFIX}-postgresql"
         #"${MINGW_PACKAGE_PREFIX}-protobuf-c"
         "${MINGW_PACKAGE_PREFIX}-proj"
         "${MINGW_PACKAGE_PREFIX}-gdal"
         "${MINGW_PACKAGE_PREFIX}-sfcgal")
options=('staticlibs' 'strip')
source=("https://download.osgeo.org/postgis/source/${_realname}-${pkgver}.tar.gz"
        pg_config
        0001-clang-postgresql.patch)
sha256sums=('91be800a72d748c5a3a4a00d82ac1de42023e29da61ece6ebf9c77fe228fcb1a'
            '3cd5a095cd4de7cb7d5f5fa9dbc02dfe02297ae1743c2961e70d9110d214f64f'
            '5e3a39bdacbbb6825206df61c49a0479da8d6201ff78423fc0bdbeaf44b70e3d')

apply_patch_with_msg() {
  for _fname in "$@"
  do
    msg2 "Applying ${_fname}"
    patch -Nbp1 -i "${srcdir}"/${_fname}
  done
}

prepare() {
  cd ${_realname}-${pkgver}

  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    apply_patch_with_msg \
      0001-clang-postgresql.patch
  fi

  ./autogen.sh
}

build() {
  [[ -d "${srcdir}"/build-${MSYSTEM} ]] && rm -rf "${srcdir}"/build-${MSYSTEM}
  cp -r ${_realname}-${pkgver} "${srcdir}"/build-${MSYSTEM} && cd "${srcdir}"/build-${MSYSTEM}

  CXXFLAGS+=" -std=gnu++17"

  # workaround to fix linking PostgreSQL with clang
  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    export LIBS="-lc++"
  fi

  ./configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --target=${MINGW_CHOST} \
    --without-protobuf \
    --with-pgconfig=${srcdir}/pg_config

  make
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  make DESTDIR="${pkgdir}" install
}
